package com.heng.groupchat.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.gson.Gson;
import com.heng.groupchat.common.BaseResponse;
import com.heng.groupchat.common.ResultUtils;
import com.heng.groupchat.model.entity.ChatRecord;
import com.heng.groupchat.model.vo.ChatRecordVO;
import com.heng.groupchat.service.ChatRecordService;
import com.heng.groupchat.service.UserService;
import com.heng.groupchat.websocket.WebSocket;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/chat")
public class ChatController {
    @Resource
    private WebSocket webSocket;

    @Resource
    private ChatRecordService chatRecordService;

    @Resource
    private UserService userService;

    @GetMapping("/send")
    public BaseResponse<Boolean> sendMessage(String content, HttpServletRequest request) {
        ChatRecord chatRecord = new ChatRecord();
        chatRecord.setUsername(userService.getCurrentUser(request).getUsername());
        chatRecord.setContent(content);
        chatRecordService.save(chatRecord);
        ChatRecordVO recordVO = ChatRecordVO.objToVO(chatRecord);
        Gson gson = new Gson();
        String recordVOJson = gson.toJson(recordVO);
        webSocket.sendAllMessage("{\"message\":"+recordVOJson+"}");
        return ResultUtils.success(true);
    }

    @GetMapping("/get")
    public BaseResponse<List<ChatRecordVO>> getChatRecords() {
        List<ChatRecord> recordList = chatRecordService.list();
        List<ChatRecordVO> recordVOList =
            recordList.stream().map(ChatRecordVO::objToVO).collect(Collectors.toList());
        return ResultUtils.success(recordVOList);
    }
}